import { disableTips, tableHeight } from "@/filters/filters";
export default {
  name: "RoleList",
  data() {
    return {
      searchCol: {
        name: '',
        page: 1,
        size: 10
      },
      height: 0,
      roleData: [],
      total: 0,

      dialogTitle: "添加角色",
      dialogFlag: false,
      roleForm: {
        name: '',
        roleRange: null
      },
      editUuid: '',

      menus: [],
      props: {
        label: 'title',
        children: 'childrens'
      },
      defaultCheckedKeys: [],
      isDisable: false,

      // icon为空的子页面数据源
			iconIsNullMenuList: []
    }
  },
  mounted() {
    this.getMenus();
    this.getRoleList();
		this.$nextTick(() => {
			this.height = tableHeight();
		});
  },
  methods: {
    getMenus() {
      this.menus = JSON.parse(sessionStorage.getItem("routeData"));
      this.dealMenuList(this.menus);
      console.log("menuList", this.menus);
    },
    dealIconIsNullNode() {
			// this.iconIsNullMenuList.forEach(item => {
      //   if (this.$refs.menuTree) {
      //     this.$refs.menuTree.remove(item);
      //   }
			// });
		},
    dealMenuList(menuList) {
      if (menuList) {
				menuList.forEach(menuItem => {
          if (!menuItem.icon && menuItem.shiroKey.indexOf('m_') !== -1) {
						this.iconIsNullMenuList.push(menuItem);
					}

					if (!menuItem.buttons) {
						menuItem.buttons = [];
					}
					// console.log(menuItem.buttons)
					if (typeof menuItem.buttons !== 'string') {
						menuItem.buttons = JSON.stringify(menuItem.buttons);
					}
					menuItem.buttons = JSON.parse(menuItem.buttons);
					menuItem.buttons.forEach(buttonItem => {
						buttonItem.title = buttonItem.name;
					});
					if (!menuItem.childrens) {
						menuItem.childrens = [];
					}
					menuItem.childrens.push(...menuItem.buttons);
					if (menuItem.children && menuItem.children.length > 0) {
						menuItem.childrens.push(...menuItem.children);
						this.dealMenuList(menuItem.childrens);
					}
				});
			} else {
				return [];
			}
    },
    handleSizeChange(newSize) {
			this.searchCol.size = newSize;
			this.getRoleList();
		},
		//监听 页码值 改变的事件
		handleCurrentChange(newPage) {
			this.searchCol.page = newPage;
			this.getRoleList();
		},
    menuCheckChange(data, checked, indeterminate) {
      console.log('data', data);
      console.log('checked', checked);
      console.log('indeterminate', indeterminate);

      // 父节点
      let parentNode =  this.$refs.menuTree.getNode(data).parent;
      parentNode.checked = checked;
    },
    getRoleList() {
      this.roleData.splice(0, this.roleData.length);

      this.$axios({
				method: "post",
				url: "api/sys/sysRole/page",
				data: this.searchCol,
        timeout: 20000
			}).then(res => {
        if (res.data.code === 200) {
					this.roleData = res.data.data;
					this.total = res.data.pageData.totalElements;
				} else {
					this.$message({
						message: "角色获取失败",
						type: "error"
					});
				}
      });
    },
    doAddRole() {
      this.dialogFlag = true;
      this.dialogTitle = "添加角色";
      this.$nextTick(() => {
				if (this.$refs.roleForm !== undefined) {
					this.$refs.roleForm.resetFields();
				}

        this.dealIconIsNullNode();
			});
    },
    submitAddRole() {
      if(this.roleForm.name === null || this.roleForm.name === '') {
        this.$message({
          message: '请输入角色名称',
          type: "error"
        });
        return;
      }

      let checkedRoles = this.$refs.menuTree.getCheckedNodes(false, true);
      if(checkedRoles === null || checkedRoles.length === 0) {
        this.$message({
          message: '请选择对应的权限',
          type: "error"
        });
        return;
      }

      console.log('checkedRoles', checkedRoles);
      console.log('checkedkkk', this.$refs.menuTree.getCheckedKeys(false, true));

      let isParentSelect = true, selNode = null;
      checkedRoles.forEach(item => {
        let node = this.$refs.menuTree.getNode(item);
        if (node !== null & node.level !== 1) {
          if(node.parent !== null && node.parent.checked === false) {
            isParentSelect = false;
            selNode = node;
            return;
          }
        }
      });

      if (!isParentSelect) {
        this.$message({
          message: '请将‘' + selNode.data.title + '’权限的上级也一同选中，才可以保存。',
          type: "error"
        });
        return;
      }

      // 创建时，若【是否需要管理范围】不选，则默认不需要
      if (this.roleForm.roleRange === null) {
        this.roleForm.roleRange = 0;
      }

      // 菜单和按钮的shiro字符串
			let descriptionSet = new Set();
      checkedRoles.forEach(item => {
				// 菜单、按钮的shiroKey按照","分隔
				descriptionSet.add(item.shiroKey);
				if (item.subPageKey) {
					descriptionSet.add(item.subPageKey);
				}
				if (item.cascadeKey) {
					descriptionSet.add(item.cascadeKey);
				}
			});

      this.roleForm.description = Array.from(descriptionSet).join();

      // console.log('---sds---:', this.roleForm.description);

      // let checkedKeys = [];
      // for(let i = 0; i < checkedRoles.length; i++) {
      //   checkedKeys.push(checkedRoles[i].shiroKey);
      // }

      // let rolesKey = checkedKeys.join(',');
      // this.roleForm.description = rolesKey;

      if(this.editUuid !== "") {
        const updateForm = {
          ...this.roleForm,
          "uuid": this.editUuid
        };
        this.$axios.post("api/sys/sysRole/update", updateForm).then(res => {
          if (res.data.code == 200) {
            this.$message({
              message: '角色更新成功',
              type: "success"
            });
            this.closeDialog();
            this.getRoleList();
          } else {
            this.$message({
              message: res.data.message,
              type: "error"
            });
          }
        });
      } else {
        this.$axios.post("api/sys/sysRole/create", this.roleForm).then(res => {
          if (res.data.code == 200) {
            this.$message({
              message: '角色添加成功',
              type: "success"
            });
            this.closeDialog();
            this.getRoleList();
          } else {
            this.$message({
              message: res.data.message,
              type: "error"
            });
          }
        });
      }
    },
    closeDialog() {
			this.dialogFlag = false;
      this.roleForm = {
        name: ''
      };
      this.defaultCheckedKeys = [];
      this.editUuid = '';
      this.isDisable = false;
		},
    async setStatus(data, status) {
      const isNext = status !== 0 || await disableTips(this.$confirm);
      if (isNext) {
        this.$axios.post('api/sys/sysRole/updateStatus', {
					status: status,
					uuid: data.uuid
				}).then(res => {
					if (res.data.code == 200) {
						this.getRoleList();
					} else {
						this.$message({
							message: status ? '启用失败' : '禁用失败',
							type: "error"
						});
					}
				});
      }
    },
    doEdit(row) {
      let roles = row.description.split(',');
      for(let i = 0; i < roles.length; i++) {
        this.defaultCheckedKeys.push(roles[i]);
      }

      this.dialogTitle = "编辑角色";
      this.roleForm.name = row.name;
      this.roleForm.roleRange = row.roleRange;
      this.editUuid = row.uuid;
      this.dialogFlag = true;

      this.$nextTick(() => {
        this.dealIconIsNullNode();
			});
    },
    doDetail(row) {
      let roles = row.description.split(',');
      for(let i = 0; i < roles.length; i++) {
        this.defaultCheckedKeys.push(roles[i]);
      }

      this.dialogTitle = "查看角色与权限";
      this.roleForm.name = row.name;
      this.roleForm.roleRange = row.roleRange;
      this.editUuid = row.uuid;
      this.dialogFlag = true;

      this.isDisable = true;

      this.$nextTick(() => {
        this.dealIconIsNullNode();
			});
    }
  }
}